'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '../contexts/AuthContext';
import Layout from '../components/Layout';
import { IconChevronRight, IconScale, IconRun, IconTarget, IconLoader2 } from '@tabler/icons-react';

interface FormData {
  height: string;
  weight: string;
  age: string;
  gender: 'male' | 'female';
  activityLevel: string;
  goal: string;
  restrictions: string[];
}

// 添加推荐结果的类型定义
interface Recommendation {
  dailyCalories: number;
  macronutrients: {
    protein: number;
    carbs: number;
    fat: number;
  };
  mealPlan: {
    breakfast: string[];
    lunch: string[];
    dinner: string[];
    snacks: string[];
  };
  advice: string;
  tips: string[];
}

export default function DietRecommend() {
  const { user, loading: authLoading } = useAuth();
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState<FormData>({
    height: '',
    weight: '',
    age: '',
    gender: 'male',
    activityLevel: 'moderate',
    goal: 'maintain',
    restrictions: [],
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [recommendation, setRecommendation] = useState<Recommendation | null>(null);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!authLoading && !user) {
      router.push('/login?redirect=/diet-recommend');
    }
  }, [user, authLoading, router]);

  // 如果正在加载或未登录，显示加载状态
  if (authLoading || !user) {
    return (
      <Layout>
        <div className="flex items-center justify-center min-h-screen">
          <div className="bg-white p-6 rounded-lg flex items-center space-x-4">
            <IconLoader2 className="w-6 h-6 animate-spin text-blue-600" />
            <span>加载中...</span>
          </div>
        </div>
      </Layout>
    );
  }

  const activityLevels = [
    { value: 'sedentary', label: '久坐不动', description: '每天的运动量很少' },
    { value: 'light', label: '轻度活动', description: '每周运动1-3次' },
    { value: 'moderate', label: '中度活动', description: '每周运动3-5次' },
    { value: 'active', label: '积极活动', description: '每周运动6-7次' },
    { value: 'very_active', label: '非常活跃', description: '每天高强度运动或体力劳动' },
  ];

  const goals = [
    { value: 'lose', label: '减重', description: '健康地减轻体重' },
    { value: 'maintain', label: '保持体重', description: '维持当前体重' },
    { value: 'gain', label: '增重', description: '健康地增加体重' },
  ];

  const dietaryRestrictions = [
    { value: 'vegetarian', label: '素食' },
    { value: 'vegan', label: '纯素' },
    { value: 'gluten_free', label: '无麸质' },
    { value: 'lactose_free', label: '无乳糖' },
    { value: 'nut_free', label: '无坚果' },
  ];

  const validateForm = () => {
    if (!formData.height || Number(formData.height) < 100 || Number(formData.height) > 250) {
      setError('请输入有效的身高（100-250cm）');
      return false;
    }
    if (!formData.weight || Number(formData.weight) < 30 || Number(formData.weight) > 200) {
      setError('请输入有效的体重（30-200kg）');
      return false;
    }
    if (!formData.age || Number(formData.age) < 12 || Number(formData.age) > 120) {
      setError('请输入有效的年龄（12-120岁）');
      return false;
    }
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    
    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);
    try {
      const res = await fetch('/api/diet/recommend', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
        credentials: 'include',
      });

      if (!res.ok) {
        const error = await res.json();
        throw new Error(error.message || '生成推荐失败');
      }

      const data = await res.json();
      setRecommendation(data.recommendation);
    } catch (error: any) {
      console.error('获取推荐失败:', error);
      setError(error.message || '生成推荐失败，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleSaveRecommendation = async () => {
    if (!recommendation) return;
    
    try {
      const res = await fetch('/api/diet/save', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          formData,
          recommendation,
        }),
        credentials: 'include',
      });

      if (!res.ok) {
        const error = await res.json();
        throw new Error(error.message || '保存失败');
      }

      alert('保存成功！');
    } catch (error: any) {
      console.error('保存失败:', error);
      alert(error.message || '保存失败，请重试');
    }
  };

  const renderStep1 = () => (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold flex items-center gap-2">
        <IconScale className="w-5 h-5" />
        基本信息
      </h3>
      <div className="grid md:grid-cols-2 gap-6">
        <div className="space-y-2">
          <label className="block text-sm font-medium text-gray-700">身高 (cm)</label>
          <input
            type="number"
            value={formData.height}
            onChange={(e) => setFormData({ ...formData, height: e.target.value })}
            className="input-field w-full"
            placeholder="请输入身高"
            required
          />
        </div>
        <div className="space-y-2">
          <label className="block text-sm font-medium text-gray-700">体重 (kg)</label>
          <input
            type="number"
            value={formData.weight}
            onChange={(e) => setFormData({ ...formData, weight: e.target.value })}
            className="input-field w-full"
            placeholder="请输入体重"
            required
          />
        </div>
        <div className="space-y-2">
          <label className="block text-sm font-medium text-gray-700">年龄</label>
          <input
            type="number"
            value={formData.age}
            onChange={(e) => setFormData({ ...formData, age: e.target.value })}
            className="input-field w-full"
            placeholder="请输入年龄"
            required
          />
        </div>
        <div className="space-y-2">
          <label className="block text-sm font-medium text-gray-700">性别</label>
          <div className="grid grid-cols-2 gap-4">
            <button
              type="button"
              onClick={() => setFormData({ ...formData, gender: 'male' })}
              className={`px-4 py-2 rounded-lg border ${
                formData.gender === 'male'
                  ? 'border-blue-500 bg-blue-50 text-blue-700'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
            >
              男性
            </button>
            <button
              type="button"
              onClick={() => setFormData({ ...formData, gender: 'female' })}
              className={`px-4 py-2 rounded-lg border ${
                formData.gender === 'female'
                  ? 'border-blue-500 bg-blue-50 text-blue-700'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
            >
              女性
            </button>
          </div>
        </div>
      </div>
      <div className="flex justify-end">
        <button
          type="button"
          onClick={() => setStep(2)}
          className="btn-primary flex items-center space-x-2"
        >
          <span>下一步</span>
          <IconChevronRight className="w-4 h-4" />
        </button>
      </div>
    </div>
  );

  const renderStep2 = () => (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold flex items-center gap-2">
        <IconRun className="w-5 h-5" />
        活动水平
      </h3>
      <div className="grid gap-4">
        {activityLevels.map((level) => (
          <button
            key={level.value}
            type="button"
            onClick={() => setFormData({ ...formData, activityLevel: level.value })}
            className={`text-left p-4 rounded-lg border ${
              formData.activityLevel === level.value
                ? 'border-blue-500 bg-blue-50'
                : 'border-gray-200 hover:border-gray-300'
            }`}
          >
            <div className="font-medium">{level.label}</div>
            <div className="text-sm text-gray-500 mt-1">{level.description}</div>
          </button>
        ))}
      </div>
      <div className="flex justify-between">
        <button
          type="button"
          onClick={() => setStep(1)}
          className="btn-primary bg-gray-500 hover:bg-gray-600"
        >
          返回
        </button>
        <button
          type="button"
          onClick={() => setStep(3)}
          className="btn-primary flex items-center space-x-2"
        >
          <span>下一步</span>
          <IconChevronRight className="w-4 h-4" />
        </button>
      </div>
    </div>
  );

  const renderStep3 = () => (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold flex items-center gap-2">
        <IconTarget className="w-5 h-5" />
        健康目标
      </h3>
      <div className="grid gap-4">
        {goals.map((goal) => (
          <button
            key={goal.value}
            type="button"
            onClick={() => setFormData({ ...formData, goal: goal.value })}
            className={`text-left p-4 rounded-lg border ${
              formData.goal === goal.value
                ? 'border-blue-500 bg-blue-50'
                : 'border-gray-200 hover:border-gray-300'
            }`}
          >
            <div className="font-medium">{goal.label}</div>
            <div className="text-sm text-gray-500 mt-1">{goal.description}</div>
          </button>
        ))}
      </div>
      <div className="space-y-4">
        <label className="block text-sm font-medium text-gray-700">饮食限制（可多选）</label>
        <div className="flex flex-wrap gap-3">
          {dietaryRestrictions.map((restriction) => (
            <button
              key={restriction.value}
              type="button"
              onClick={() => {
                const newRestrictions = formData.restrictions.includes(restriction.value)
                  ? formData.restrictions.filter((r) => r !== restriction.value)
                  : [...formData.restrictions, restriction.value];
                setFormData({ ...formData, restrictions: newRestrictions });
              }}
              className={`px-4 py-2 rounded-lg border ${
                formData.restrictions.includes(restriction.value)
                  ? 'border-blue-500 bg-blue-50 text-blue-700'
                  : 'border-gray-200 hover:border-gray-300'
              }`}
            >
              {restriction.label}
            </button>
          ))}
        </div>
      </div>
      <div className="flex justify-between">
        <button
          type="button"
          onClick={() => setStep(2)}
          className="btn-primary bg-gray-500 hover:bg-gray-600"
        >
          返回
        </button>
        <button type="submit" className="btn-primary">
          生成推荐
        </button>
      </div>
    </div>
  );

  // 修改 renderResult 添加保存按钮
  const renderResult = () => (
    <div className="space-y-8">
      <div className="flex justify-between items-center">
        <h3 className="text-lg font-semibold">推荐结果</h3>
        <div className="space-x-4">
          <button
            type="button"
            onClick={handleSaveRecommendation}
            className="btn-primary"
          >
            保存推荐
          </button>
          <button
            type="button"
            onClick={() => {
              setRecommendation(null);
              setStep(1);
            }}
            className="text-blue-600 hover:text-blue-700"
          >
            重新生成
          </button>
        </div>
      </div>

      {/* 每日摄入量 */}
      <div className="grid md:grid-cols-4 gap-4">
        <div className="bg-blue-50 p-4 rounded-lg">
          <div className="text-sm text-gray-600">每日推荐热量</div>
          <div className="text-xl font-bold text-blue-600">
            {recommendation?.dailyCalories} 千卡
          </div>
        </div>
        <div className="bg-green-50 p-4 rounded-lg">
          <div className="text-sm text-gray-600">蛋白质</div>
          <div className="text-xl font-bold text-green-600">
            {recommendation?.macronutrients.protein}g
          </div>
        </div>
        <div className="bg-yellow-50 p-4 rounded-lg">
          <div className="text-sm text-gray-600">碳水化合物</div>
          <div className="text-xl font-bold text-yellow-600">
            {recommendation?.macronutrients.carbs}g
          </div>
        </div>
        <div className="bg-red-50 p-4 rounded-lg">
          <div className="text-sm text-gray-600">脂肪</div>
          <div className="text-xl font-bold text-red-600">
            {recommendation?.macronutrients.fat}g
          </div>
        </div>
      </div>

      {/* 一日三餐推荐 */}
      <div className="space-y-4">
        <h4 className="font-medium">一日三餐推荐</h4>
        <div className="grid md:grid-cols-3 gap-4">
          <div className="border rounded-lg p-4">
            <div className="font-medium mb-2">早餐</div>
            <ul className="list-disc list-inside text-gray-600 space-y-1">
              {recommendation?.mealPlan.breakfast.map((item, index) => (
                <li key={index}>{item}</li>
              ))}
            </ul>
          </div>
          <div className="border rounded-lg p-4">
            <div className="font-medium mb-2">午餐</div>
            <ul className="list-disc list-inside text-gray-600 space-y-1">
              {recommendation?.mealPlan.lunch.map((item, index) => (
                <li key={index}>{item}</li>
              ))}
            </ul>
          </div>
          <div className="border rounded-lg p-4">
            <div className="font-medium mb-2">晚餐</div>
            <ul className="list-disc list-inside text-gray-600 space-y-1">
              {recommendation?.mealPlan.dinner.map((item, index) => (
                <li key={index}>{item}</li>
              ))}
            </ul>
          </div>
        </div>
        <div className="border rounded-lg p-4">
          <div className="font-medium mb-2">零食建议</div>
          <ul className="list-disc list-inside text-gray-600 space-y-1">
            {recommendation?.mealPlan.snacks.map((item, index) => (
              <li key={index}>{item}</li>
            ))}
          </ul>
        </div>
      </div>

      {/* 建议和提示 */}
      <div className="space-y-4">
        <div className="bg-gray-50 rounded-lg p-4">
          <h4 className="font-medium mb-2">饮食建议</h4>
          <p className="text-gray-600 whitespace-pre-line">{recommendation?.advice}</p>
        </div>
        <div className="bg-gray-50 rounded-lg p-4">
          <h4 className="font-medium mb-2">注意事项</h4>
          <ul className="list-disc list-inside text-gray-600 space-y-1">
            {recommendation?.tips.map((tip, index) => (
              <li key={index}>{tip}</li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );

  return (
    <Layout>
      <div className="max-w-6xl mx-auto">
        <div className="bg-white p-8">
          <h2 className="text-2xl font-bold mb-8">个性化饮食推荐</h2>
          
          {error && (
            <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
              {error}
            </div>
          )}

          {recommendation ? (
            renderResult()
          ) : (
            <form onSubmit={handleSubmit}>
              {step === 1 && renderStep1()}
              {step === 2 && renderStep2()}
              {step === 3 && (
                <>
                  {renderStep3()}
                  {isSubmitting && (
                    <div className="fixed inset-0 bg-black/50 flex items-center justify-center">
                      <div className="bg-white p-6 rounded-lg flex items-center space-x-4">
                        <IconLoader2 className="w-6 h-6 animate-spin text-blue-600" />
                        <span>生成推荐中...</span>
                      </div>
                    </div>
                  )}
                </>
              )}
            </form>
          )}
        </div>
      </div>
    </Layout>
  );
} 